import { setLocal, getLocal, delLocal } from './storage.js'

/**
 * 时间格式化
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return ''
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      time = time.replace(/-/g, '/')
    }
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || '0'
  })
  return time_str
}

/**
 * 生成全局唯一标识符 guid
 */
function guid() {
  const S4 = () => (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  // 因为第一个字符为数值时,该 guid 不能用作 id 或者 class 所以前面加个 guid 前缀
  return `guid${S4()}${S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`;
}

// 获取微信code
function getCode() {
  return new Promise((resolve, reject) => {
    wx.login({
      success(res) {
        resolve(res.code)
      },
      fail(err) { reject(err) },
    })
  })
}


/**
 * 提示信息 -- 微信小程序
 * @parame String
 * @return 弹窗显示
 */
function tips(title = '提示', icon) {
  let config = {
    title: title,
    icon: 'none',
    mask: true
  };
  if (icon) {
    config.icon = 'success';
  }
  wx.showToast(config);
}

/**
 * 微信模态弹窗 -- 微信小程序
 * @param title:String, content:String
 * @return Promise  Boolean
 */
function showModal(content = '', title = '温馨提示', showCancel) {
  return new Promise((resolve, reject) => {
    wx.showModal({
      title: title,
      content: content,
      showCancel: showCancel,
      success: (res) => {
        if (res.confirm) {
          resolve(true)
        } else if (res.cancel) {
          resolve(false)
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

export default {
  tips,
  showModal,
  guid,
  parseTime,
  getCode,
  setLocal,
  getLocal,
  delLocal,
}